from sanic import Sanic, json, response, HTTPResponse, Request
# from sanic_jwt import inject_user
from tortoise.contrib.sanic import register_tortoise
from tortoise.transactions import in_transaction

from config import db_config, Config
from user import user_blueprint
from user.new_views import UserView
from sanic_session import Session, RedisSessionInterface
from sanic_cors import CORS
from sanic_auth import Auth, User
from sanic_ext import Extend

from utils.decorator import login_required
from tasks.tasks import all_jobs
from utils.redis_utils import sanic_redis
# import sentry_sdk
# from sentry_sdk.integrations.sanic import SanicIntegration
#
# # 服务监控
# sentry_sdk.init(
#     dsn="https://98fdfb0b99e2495b8eb25e94640e0312@127.0.0.1:9000/0",
#     integrations=[SanicIntegration()]
# )

app = Sanic(__name__)
app.config.FORWARDED_SECRET = ",$FCyFZ^b16#m:ragM#d-!;4!U5zgZfe(EhswOL_HGV#xN1Ll%MaBU42AN=jXgp7"
app.config.WTF_CSRF_SECRET_KEY = "csrf key for sanic web"
Session(app, interface=RedisSessionInterface(sanic_redis.redis_pool))
Extend(app)
CORS(app)
app.config.AUTH_LOGIN_ENDPOINT = "login"

# 1. Config = "settings.py"
# 2. Config = {"SANIC_A": 1, "SANIC_B": 2}
# 3.. Config => class Config:
#               SANIC_A = 1
#               SANIC_B = 2
app.update_config(Config)

# generate_schemas 启动app时，是否创建数据表
register_tortoise(
    app, config=db_config,
    modules={
        "models": ["models"]
    },
    generate_schemas=False
)

app.blueprint(user_blueprint)

app.config.API_TITLE = "Borden System API"
app.config.API_CONTACT_EMAIL = "zuodb@amoydx.com"
app.config.API_LICENSE_NAME = "Borden Zuo"

# app.add_task(all_jobs)


@app.middleware("request")
def cors_middle_req(request):
    """路由需要启用OPTIONS方法"""
    if request.method == 'OPTIONS':
        allow_headers = [
            'access_token',
            'Content-Type'
        ]
        headers = {
            'Access-Control-Allow-Methods':
                ', '.join(request.app.router.get_supported_methods(request.path)),
            'Access-Control-Max-Age': '86400',
            'Access-Control-Allow-Headers': ', '.join(allow_headers),
        }
        return HTTPResponse('', headers=headers)


@app.middleware("response")
def cors_middle_res(request: Request, resp: HTTPResponse):
    """跨域处理"""
    print(request.path)
    allow_origin = '*'
    resp.headers.update(
        {
            'Access-Control-Allow-Origin': allow_origin,
        }
    )


auth = Auth(app)
app.add_route(UserView.as_view(), "/api/user")


@app.route("/login", methods=["POST"])
async def login(request):
    if request.method == "POST":
        username = request.json.get("username")
        password = request.json.get("password")
        if username == "admin" and password == "123456":
            # 事务
            async with in_transaction():
                user = User(id=1, name=username)
                auth.login_user(request, user)
            return response.redirect("/profile")  # json({"user": user})


@app.route("/profile")
@auth.login_required(user_keyword="user")
# @inject_user()
async def profile(request, user):
    print(request)
    return json({"user": user})


@app.route("/index")
@login_required
async def hello(request):
    cookie = request.cookies
    print(cookie)
    await all_jobs()
    return json({"hello": "world"})


if __name__ == '__main__':
    debug = False
    access = True
    app.run(port=9898, access_log=access, debug=debug)
